package com.studentbook.servlet;

import com.studentbook.bean.StudentContact;
import com.studentbook.service.StudentContactService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 从文件加载通讯录信息Servlet
 */
@WebServlet("/loadContactsFromFile")
public class LoadContactsFromFileServlet extends HttpServlet {
    private StudentContactService contactService = new StudentContactService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取文件路径参数（可选）
        String filePath = request.getParameter("filePath");
        
        try {
            // 从文件加载通讯录信息
            List<StudentContact> contactList = contactService.loadContactsFromFile(filePath);
            
            // 将加载的联系人列表放入请求属性
            request.setAttribute("contactList", contactList);
            request.setAttribute("message", "成功从文件加载" + contactList.size() + "条联系人信息！");
            
            // 转发到联系人列表页面
            request.getRequestDispatcher("/list.jsp").forward(request, response);
        } catch (Exception e) {
            // 处理异常
            request.setAttribute("message", "从文件加载联系人信息失败：" + e.getMessage());
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}